package bjut.core.factory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/9 20:59
 */
public final class SingletonFactory {

    private static final ConcurrentHashMap<String, Object> INSTANCE_MAP = new ConcurrentHashMap<>();

    public static <T> T getInstance(Class<T> cls) {

        if (cls == null) {
            throw new IllegalArgumentException();
        }
        String key = cls.toString();
        Object instance = INSTANCE_MAP.get(key);
        if (instance == null) {
            instance = INSTANCE_MAP.computeIfAbsent(key, v -> {
                try {
                    return cls.newInstance();
                } catch (Exception exception) {
                    throw new RuntimeException(exception.getMessage(), exception);
                }
            });
        }
        return cls.cast(instance);
    }

}
